package com.zzedu.web.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.zzedu.common.annotation.Log;
import com.zzedu.common.core.controller.BaseController;
import com.zzedu.common.core.domain.AjaxResult;
import com.zzedu.common.core.domain.entity.SysDept;
import com.zzedu.common.core.domain.entity.SysRole;
import com.zzedu.common.core.domain.entity.SysUser;
import com.zzedu.common.core.page.TableDataInfo;
import com.zzedu.common.core.text.Convert;
import com.zzedu.common.enums.BusinessType;
import com.zzedu.common.enums.UserTypeEnumns;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.common.utils.poi.ExcelUtil;
import com.zzedu.framework.web.service.SysPasswordService;
import com.zzedu.system.service.ISysDeptService;
import com.zzedu.system.service.ISysPostService;
import com.zzedu.system.service.ISysRoleService;
import com.zzedu.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author smarthome
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysPasswordService passwordService;


    @PreAuthorize("@permission.hasAnyPermissions('system:user:list')")
    @RequestMapping("/list")
    public TableDataInfo list(@RequestBody SysUser user) {
        IPage<SysUser> list = userService.selectUserList(user.getPageDTO(), user);
        return getDataTable(list);
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:user:list')")
    @RequestMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    @PreAuthorize("@permission.hasAnyPermissions('system:user:export')")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(new Page<>(1, -1), user).getRecords();
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @PreAuthorize("@permission.hasAnyPermissions('system:user:import')")
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String message = "";//userService.importUser(userList, updateSupport, getLoginName());
        return AjaxResult.success(message);
    }

    @PreAuthorize("@permission.hasAnyPermissions('system:user:view')")
    @RequestMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }


    /**
     * 新增保存用户
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        user.setUserType(UserTypeEnumns.PLATFORM.getCode());
        user.setPassword(passwordService.encryptPassword(user.getPassword()));
        return toAjax(userService.save(user));
    }

    /**
     * 修改保存用户
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        return toAjax(userService.updateById(user));
    }

    @PreAuthorize("@permission.hasAnyPermissions('system:user:resetPwd')")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    public AjaxResult resetPwdSave(@RequestBody SysUser user) {
        user.setPassword(passwordService.encryptPassword(user.getPassword()));
        if (userService.updateById(user)) {
            return success();
        }
        return error();
    }


    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:user:query')")
    @RequestMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }


    /**
     * 用户授权角色
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @RequestMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @PreAuthorize("@permission.hasAnyPermissions('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @RequestMapping("/remove/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.removeBatchByIds(Arrays.stream(userIds).collect(Collectors.toList())));
    }

    /**
     * 用户状态修改
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        return toAjax(userService.updateById(user));
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", Optional.ofNullable(roleService.selectRolesByUserId(userId)).orElse(Lists.newArrayList()).stream().map(SysRole::getId).collect(Collectors.toList()));
        }
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        return ajax;
    }

}